import { openDB } from 'idb';

const DB_NAME = 'DecorationDB';
const DB_VERSION = 1;

export async function initDB() {
  const db = await openDB(DB_NAME, DB_VERSION, {
    upgrade(db) {
      // 创建存储贴纸的对象仓库
      if (!db.objectStoreNames.contains('stickers')) {
        const stickersStore = db.createObjectStore('stickers', { keyPath: 'id' });
        stickersStore.createIndex('type', 'type');
        stickersStore.createIndex('category', 'category');
      }

      // 创建存储收藏项的对象仓库
      if (!db.objectStoreNames.contains('favorites')) {
        const favoritesStore = db.createObjectStore('favorites', { keyPath: 'id' });
        favoritesStore.createIndex('type', 'type');
      }

      // 创建存储自定义上传内容的对象仓库
      if (!db.objectStoreNames.contains('uploads')) {
        const uploadsStore = db.createObjectStore('uploads', { keyPath: 'id' });
        uploadsStore.createIndex('type', 'type');
        uploadsStore.createIndex('createDate', 'createDate');
      }
    },
  });

  return db;
}

export async function addItem(storeName, item) {
  const db = await initDB();
  const tx = db.transaction(storeName, 'readwrite');
  const store = tx.objectStore(storeName);
  await store.add(item);
}

export async function getItem(storeName, id) {
  const db = await initDB();
  const tx = db.transaction(storeName, 'readonly');
  const store = tx.objectStore(storeName);
  return store.get(id);
}

export async function getAllItems(storeName) {
  const db = await initDB();
  const tx = db.transaction(storeName, 'readonly');
  const store = tx.objectStore(storeName);
  return store.getAll();
}

export async function updateItem(storeName, item) {
  const db = await initDB();
  const tx = db.transaction(storeName, 'readwrite');
  const store = tx.objectStore(storeName);
  await store.put(item);
}

export async function deleteItem(storeName, id) {
  const db = await initDB();
  const tx = db.transaction(storeName, 'readwrite');
  const store = tx.objectStore(storeName);
  await store.delete(id);
}

export async function getItemsByType(storeName, type) {
  const db = await initDB();
  const tx = db.transaction(storeName, 'readonly');
  const store = tx.objectStore(storeName);
  const typeIndex = store.index('type');
  return typeIndex.getAll(type);
}
